{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "59965cab",
   "metadata": {},
   "source": [
    "<a href=\"https://colab.research.google.com/github/jerryjliu/llama_index/blob/main/docs/examples/docstore/DynamoDBDocstoreDemo.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "29ec3720",
   "metadata": {},
   "source": [
    "If you're opening this Notebook on colab, you will probably need to install LlamaIndex 🦙."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "aeda26eb",
   "metadata": {},
   "outputs": [],
   "source": [
    "!pip install llama-index"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a54d1c43-4b7f-4917-939f-a964f6f3dafc",
   "metadata": {},
   "outputs": [],
   "source": [
    "import nest_asyncio\n",
    "\n",
    "nest_asyncio.apply()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "fa67fa07-1395-4aab-a356-72bdb302f6b2",
   "metadata": {},
   "outputs": [],
   "source": [
    "import logging\n",
    "import sys\n",
    "import os\n",
    "\n",
    "logging.basicConfig(stream=sys.stdout, level=logging.INFO)\n",
    "logging.getLogger().addHandler(logging.StreamHandler(stream=sys.stdout))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1d12d766-3ca8-4012-9da2-248be80bb6ab",
   "metadata": {},
   "outputs": [],
   "source": [
    "from llama_index import (\n",
    "    SimpleDirectoryReader,\n",
    "    ServiceContext,\n",
    "    StorageContext,\n",
    ")\n",
    "from llama_index import VectorStoreIndex, SummaryIndex, SimpleKeywordTableIndex\n",
    "from llama_index.llms import OpenAI\n",
    "from llama_index.response.notebook_utils import display_response"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3d950023",
   "metadata": {},
   "source": [
    "#### Download Data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b582ec16",
   "metadata": {},
   "outputs": [],
   "source": [
    "!mkdir -p 'data/paul_graham/'\n",
    "!wget 'https://raw.githubusercontent.com/run-llama/llama_index/main/docs/examples/data/paul_graham/paul_graham_essay.txt' -O 'data/paul_graham/paul_graham_essay.txt'"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "f6dd9d5f-a601-4097-894e-fe98a0c35a5b",
   "metadata": {},
   "source": [
    "#### Load Documents"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e7cdaf9d-cfbd-4ced-8d4e-6eef8508224d",
   "metadata": {},
   "outputs": [],
   "source": [
    "reader = SimpleDirectoryReader(\"./data/paul_graham/\")\n",
    "documents = reader.load_data()"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "bae82b55-5c9f-432a-9e06-1fccb6f9fc7f",
   "metadata": {},
   "source": [
    "#### Parse into Nodes"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f97e558a-c29f-44ec-ab33-1f481da1a6ef",
   "metadata": {},
   "outputs": [],
   "source": [
    "from llama_index.node_parser import SentenceSplitter\n",
    "\n",
    "nodes = SentenceSplitter().get_nodes_from_documents(documents)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "aff4c8e1-b2ba-4ea6-a8df-978c2788fedc",
   "metadata": {},
   "source": [
    "#### Add to Docstore"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f9998976",
   "metadata": {},
   "outputs": [],
   "source": [
    "TABLE_NAME = os.environ[\"DYNAMODB_TABLE_NAME\"]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "54b9bd36",
   "metadata": {},
   "outputs": [],
   "source": [
    "from llama_index.storage.docstore.dynamodb_docstore import (\n",
    "    DynamoDBDocumentStore,\n",
    ")\n",
    "from llama_index.storage.index_store.dynamodb_index_store import (\n",
    "    DynamoDBIndexStore,\n",
    ")\n",
    "from llama_index.vector_stores.dynamodb import DynamoDBVectorStore"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1ba8b0da-67a8-4653-8cdb-09e39583a2d8",
   "metadata": {},
   "outputs": [],
   "source": [
    "storage_context = StorageContext.from_defaults(\n",
    "    docstore=DynamoDBDocumentStore.from_table_name(table_name=TABLE_NAME),\n",
    "    index_store=DynamoDBIndexStore.from_table_name(table_name=TABLE_NAME),\n",
    "    vector_store=DynamoDBVectorStore.from_table_name(table_name=TABLE_NAME),\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e88378b2",
   "metadata": {},
   "outputs": [],
   "source": [
    "storage_context.docstore.add_documents(nodes)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "528149c1-5bde-4eba-b75a-e8fa1da17d7c",
   "metadata": {},
   "source": [
    "#### Define & Add Multiple Indexes\n",
    "\n",
    "Each index uses the same underlying Node."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "316fb6ac-2031-4d17-9999-ffdb827f46d1",
   "metadata": {},
   "outputs": [],
   "source": [
    "# https://gpt-index.readthedocs.io/en/latest/api_reference/indices/list.html\n",
    "summary_index = SummaryIndex(nodes, storage_context=storage_context)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5c6b2141-fc77-4dec-891b-d4dad0633b35",
   "metadata": {},
   "outputs": [],
   "source": [
    "# https://gpt-index.readthedocs.io/en/latest/api_reference/indices/vector_store.html\n",
    "vector_index = VectorStoreIndex(nodes, storage_context=storage_context)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "144bc7eb",
   "metadata": {},
   "outputs": [],
   "source": [
    "# https://gpt-index.readthedocs.io/en/latest/api_reference/indices/table.html\n",
    "keyword_table_index = SimpleKeywordTableIndex(\n",
    "    nodes, storage_context=storage_context\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4ccbe86c",
   "metadata": {},
   "outputs": [],
   "source": [
    "# NOTE: the docstore still has the same nodes\n",
    "len(storage_context.docstore.docs)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "1059ec3c",
   "metadata": {},
   "source": [
    "#### Test out saving and loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d0f258d6",
   "metadata": {},
   "outputs": [],
   "source": [
    "# NOTE: docstore, index_store, and vector_index is persisted in DynamoDB by default when they are created\n",
    "# NOTE: You can also persist simple vector store to disk by using the command below\n",
    "storage_context.persist()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9155c1a9",
   "metadata": {},
   "outputs": [],
   "source": [
    "# note down index IDs\n",
    "list_id = summary_index.index_id\n",
    "vector_id = vector_index.index_id\n",
    "keyword_id = keyword_table_index.index_id"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "555de7fa",
   "metadata": {},
   "outputs": [],
   "source": [
    "from llama_index.indices.loading import load_index_from_storage\n",
    "\n",
    "# re-create storage context\n",
    "storage_context = StorageContext.from_defaults(\n",
    "    docstore=DynamoDBDocumentStore.from_table_name(table_name=TABLE_NAME),\n",
    "    index_store=DynamoDBIndexStore.from_table_name(table_name=TABLE_NAME),\n",
    "    vector_store=DynamoDBVectorStore.from_table_name(table_name=TABLE_NAME),\n",
    ")\n",
    "\n",
    "summary_index = load_index_from_storage(\n",
    "    storage_context=storage_context, index_id=list_id\n",
    ")\n",
    "keyword_table_index = load_index_from_storage(\n",
    "    storage_context=storage_context, index_id=keyword_id\n",
    ")\n",
    "\n",
    "# You need to add \"vector_store=DynamoDBVectorStore.from_table_name(table_name=TABLE_NAME)\" to StorageContext to load vector index from DynamoDB\n",
    "vector_index = load_index_from_storage(\n",
    "    storage_context=storage_context, index_id=vector_id\n",
    ")"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "c5bc40a7",
   "metadata": {},
   "source": [
    "#### Test out some Queries"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8db82de3",
   "metadata": {},
   "outputs": [],
   "source": [
    "chatgpt = OpenAI(temperature=0, model=\"gpt-3.5-turbo\")\n",
    "service_context_chatgpt = ServiceContext.from_defaults(\n",
    "    llm=chatgpt, chunk_size=1024\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "244bc6ae",
   "metadata": {},
   "outputs": [],
   "source": [
    "query_engine = summary_index.as_query_engine()\n",
    "list_response = query_engine.query(\"What is a summary of this document?\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6cbe77ef",
   "metadata": {},
   "outputs": [],
   "source": [
    "display_response(list_response)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "02b800ab",
   "metadata": {},
   "outputs": [],
   "source": [
    "query_engine = vector_index.as_query_engine()\n",
    "vector_response = query_engine.query(\"What did the author do growing up?\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "70b63767",
   "metadata": {},
   "outputs": [],
   "source": [
    "display_response(vector_response)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b93478b6",
   "metadata": {},
   "outputs": [],
   "source": [
    "query_engine = keyword_table_index.as_query_engine()\n",
    "keyword_response = query_engine.query(\n",
    "    \"What did the author do after his time at YC?\"\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8044da9c",
   "metadata": {},
   "outputs": [],
   "source": [
    "display_response(keyword_response)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "strat",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
